﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Microsoft.Reputation.Services
{
    public static class XMLParser
    {

        private static XmlWriterSettings xmlWriterSettings = CreateXmlWriterSettings();

        private static XmlWriterSettings CreateXmlWriterSettings()
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = false;
            xmlWriterSettings.OmitXmlDeclaration = true;
            xmlWriterSettings.NewLineChars = string.Empty;
            return xmlWriterSettings;
        }

        public static T FromXmlString<T>(string xmlString)
        {
            if ((null == xmlString) || string.IsNullOrEmpty(xmlString))
            {
                return default(T);
            }

            try
            {
                using (StringReader stringReader = new StringReader(xmlString))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    return (T)xmlSerializer.Deserialize(stringReader);
                }
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.InnerException.ToString());
                throw ex;
            }
        }


        public static string ToXmlString<T>(T theObject)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                using (XmlWriter xmlWriter = XmlWriter.Create(sb, xmlWriterSettings))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                    xmlSerializer.Serialize(xmlWriter, theObject);
                }
                return sb.ToString();
            }
            catch (InvalidOperationException ex)
            {
                Console.WriteLine(ex.InnerException.ToString());
                throw ex;
            }
        }
    }
}
